package com.ljdemo.lrecorder.model;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

/**
 * 计时器
 * <br/>
 * 创建时间 : 2023/6/20
 * */
public class Timer {

    private static final String TAG="计时器";
    private boolean isTimekeeping=false;
    private int timeCount=0;
    private static final int TIME_CHANGE=3;
    private Thread thread;
    private TimeChangeListener timeChangeListener;
    private Handler handler=new Handler(Looper.myLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            timeChangeListener.timeChange(timeCount);
            return false;
        }
    });

    public Timer(){}

    public static Timer constructor(){
        return new Timer();
    }

    public void setTimeChangeListener(TimeChangeListener timeChangeListener){
        this.timeChangeListener=timeChangeListener;
    }

    public void start(){
        isTimekeeping=true;
        thread=new Thread(new Runnable() {
            @Override
            public void run() {
                timeCount=0;
                handler.sendEmptyMessage(TIME_CHANGE);
                while (isTimekeeping){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Log.e(TAG,"线程休眠时出错");
                        throw new RuntimeException(e);
                    }
                    timeCount++;
                    handler.sendEmptyMessage(TIME_CHANGE);
                }
            }
        });
        thread.start();
    }

    public void stop(){
        isTimekeeping=false;
    }

    public interface TimeChangeListener{
        /**
         * @param time 录音时间，单位为秒
         * */
        void timeChange(int time);
    }

}
